package com.zh.ssmshirofreemarker.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.zh.ssmshirofreemarker.entity.Role;
import com.zh.ssmshirofreemarker.entity.User;
import com.zh.ssmshirofreemarker.mapper.RoleMapper;
import com.zh.ssmshirofreemarker.service.IRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZH
 * @since 2018-07-24
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public Page<Role> getAll(Page<Role> page, Role role) {
        return page.setRecords(roleMapper.selectRoleList(page,role));
    }

    @Override
    public Role getRoleById(long id) {
        Role role = null;
        try{
            role = roleMapper.selectById(id);
        } catch (Exception e){
            e.printStackTrace();
        }
        return role;
    }

    @Override
    public boolean updateRole(Role role) {
        int count = 0;
        try{
           count = roleMapper.updateById(setUpdate(role));
        } catch (Exception e){
            e.printStackTrace();
        }
        if(count > 0){
            return true;
        }
        return false;
    }

    private Role setInsert(Role role) {
        String currentUser = SecurityUtils.getSubject().getPrincipal().toString();
        Date date = new Date();
        role.setCreateTime(date);
        role.setUpdateTime(date);
        role.setCreateUser(currentUser);
        role.setUpdateUser(currentUser);
        return role;
    }

    private Role setUpdate(Role role){
        String currentUser = SecurityUtils.getSubject().getPrincipal().toString();
        Date date = new Date();
        role.setUpdateTime(date);
        role.setUpdateUser(currentUser);
        return role;
    }


    @Override
    public boolean deleteRoles(String[] ids) {
        int count  = 0;
        try{
            count = roleMapper.deleteBatchIds(Arrays.asList(ids));
        } catch (Exception e){
            e.printStackTrace();
        }
        if(count > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean addRole(Role role) {
        int count  = 0;
        try{
            count = roleMapper.insert(setInsert(role));
        } catch (Exception e){
            e.printStackTrace();
        }
        if(count > 0){
            return true;
        }
        return false;
    }

    @Override
    public List<Role> getRolesByUserId(User user) {

        return null;
    }
}
